package com.landscope.issue.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.landscope.issue.bean.E_PERMISSION_TYPE;
import com.landscope.issue.controller.api.dto.*;
import com.landscope.issue.controller.api.param.*;
import com.landscope.issue.controller.base.ResponseResult;
import com.landscope.issue.entity.Monitordata;
import com.landscope.issue.entity.Project;
import com.landscope.issue.mapper.AlarmmsgMapper;
import com.landscope.issue.mapper.MonitordataMapper;
import com.landscope.issue.mapper.ProjectMapper;
import com.landscope.issue.mapper.StainfoMapper;
import com.landscope.issue.utils.TokenUtil;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;


/**
 * @author qzp
 * @version v1.0
 * @date 2021/8/2 15:25
 **/
@Service
@Slf4j
public class ApiStaService {

    @Value("${token_valid}")
    private Boolean tokenValid;

    @Value("${report_file_url}")
    private String reportUrl;

    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private StainfoMapper stainfoMapper;
    @Resource
    private MonitordataMapper monitordataMapper;
    @Resource
    private AlarmmsgMapper alarmmsgMapper;

    public ResponseResult<List<StaListDataDto>> info(StaInfoParam param) {
        if (tokenValid) {
            // 验证token
            TokenUtil.verifyToken();
            // 验证项目权限
            TokenUtil.verifyAuthority(param.getAccessToken(), param.getProjectCode());
            // 验证功能权限
            TokenUtil.verifyRole(E_PERMISSION_TYPE.stad_en.toString());
        }

        // 获取台站实时列表信息
        List<StaListDataDto> staDataList = stainfoMapper.findDataListByCode(param.getProjectCode());
        for (StaListDataDto dto : staDataList) {
            // 经纬度保留两位小数
            dto.setLatitude(dto.getLatitude() == null ? "" : new BigDecimal(dto.getLatitude()).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
            dto.setLongitude(dto.getLongitude() == null ? "" : new BigDecimal(dto.getLongitude()).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
        }

        return new ResponseResult().success().setData(staDataList);
    }

    public ResponseResult<MonitorDataDto> changeData(ChangeDataParam param) {
        if (tokenValid) {
            // 验证token
            TokenUtil.verifyToken();

            // 验证项目权限
            TokenUtil.verifyAuthority(param.getAccessToken(), param.getProjectCode());

            // 验证功能权限
            TokenUtil.verifyRole(E_PERMISSION_TYPE.jcad_en.toString());
        }

        // 将时间进行周一到周日补全
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtil.parseDate(param.getEndTime()));
        // 将结束时间设置为周日
        if (calendar.get(Calendar.DAY_OF_WEEK) == 1) {
            calendar.add(Calendar.WEEK_OF_MONTH, -1);
        }
        calendar.add(Calendar.WEEK_OF_MONTH, 1);
        calendar.set(Calendar.DAY_OF_WEEK, 1);
        String fillEndDate = DateUtil.format(calendar.getTime(), "yyyy-MM-dd");
        Long fillEndTime = calendar.getTimeInMillis();

        calendar.setTime(DateUtil.parseDate(param.getStartTime()));
        if (calendar.get(Calendar.DAY_OF_WEEK) == 1) {
            calendar.add(Calendar.WEEK_OF_MONTH, -1);
        }
        calendar.set(Calendar.DAY_OF_WEEK, 2);
        String fillStartDate = DateUtil.format(calendar.getTime(), "yyyy-MM-dd");

        List<String> fillXData = new ArrayList<>();
        while (calendar.getTimeInMillis() <= fillEndTime) {
            fillXData.add(DateUtil.format(calendar.getTime(), "MM.dd"));
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        // 获取监测变化数据
        MonitorDataDto monitorDataDto = new MonitorDataDto();
        monitorDataDto.setEndDate(fillEndDate);
        monitorDataDto.setStartDate(fillStartDate);
        monitorDataDto.setXData(fillXData);
        monitorDataDto.setName(param.getStaName());
        // 查找时间段内，该项目的数据
        List<Monitordata> monitordataList = monitordataMapper.findByCode(param.getProjectCode(), fillStartDate, fillEndDate);

        // 获取vvig: t01_t02:-0.14;t01_t03:-0.17;t01_t04:-0.19;t02_t03:-0.05;t02_t04:-0.17;t03_t04:-0.07;
        List<String> yVvigList = new ArrayList<>();
        List<String> yKdigList = new ArrayList<>();
        MonitorDataDto.MonitorYData monitorVvig = new MonitorDataDto.MonitorYData();
        MonitorDataDto.MonitorYData monitorKdig = new MonitorDataDto.MonitorYData();

        calendar.setTime(DateUtil.parseDate(fillStartDate));
        while (calendar.getTimeInMillis() <= fillEndTime) {
            Boolean has = false;
            for (Monitordata monitordata : monitordataList) {
                String d = DateUtil.formatDate(calendar.getTime());
                if (monitordata.getDate().contains(d)) {
                    has = true;
                    // 遍历数据，解析vvig数据
                    String vvig = monitordata.getVvig();
                    String[] vvigs = vvig.split(";");
                    for (String key : vvigs) {
                        //  对比数据中台站对别名和 本次查找的台站对别名是否对应
                        String[] vs = key.split(":");
                        String name = monitorDataDto.getName();
                        name = name.replace("监测变化", "");
                        String[] names = name.split(":");
                        String[] v1s = vs[0].split("_");
                        String[] v2s = names[0].split("-");
                        if (v2s.length == 2 && ((v2s[0].contains(v1s[0]) || v2s[0].contains(v1s[1])) && (v2s[1].contains(v1s[0]) || v2s[1].contains(v1s[1])))) {
                            if (vs[1].compareTo("100") > 0)
                                yVvigList.add(null);
                            else
                                yVvigList.add(vs[1]);
                            break;
                        } else if (v2s.length == 1 && v2s[0].contains(v1s[0])) {
                            if (vs[1].compareTo("100") > 0)
                                yVvigList.add(null);
                            else
                                yVvigList.add(vs[1]);
                            break;
                        }
                    }

                    // 解析kdig数据
                    String kdig = monitordata.getKdig();
                    String[] kdigs = kdig.split(";");
                    for (String key : kdigs) {
                        String[] vs = key.split(":");
                        String name = monitorDataDto.getName();
                        name = name.replace("监测变化", "");
                        String[] names = name.split(":");
                        String[] v1s = vs[0].split("_");
                        String[] v2s = names[0].split("-");
                        if (v2s.length == 2 && ((v2s[0].contains(v1s[0]) || v2s[0].contains(v1s[1])) && (v2s[1].contains(v1s[0]) || v2s[1].contains(v1s[1])))) {
                            if (vs[1].compareTo("100") > 0)
                                yKdigList.add(null);
                            else
                                yKdigList.add(vs[1]);
                            break;
                        } else if (v2s.length == 1 && v2s[0].contains(v1s[0])) {
                            if (vs[1].compareTo("100") > 0)
                                yKdigList.add(null);
                            else
                                yKdigList.add(vs[1]);
                            break;
                        }
                    }
                    continue;
                }
            }
            if (!has) {
                yVvigList.add(null);
                yKdigList.add(null);
            }
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        monitorVvig.setYData(yVvigList);
        monitorKdig.setYData(yKdigList);
        monitorDataDto.setVvig(monitorVvig);
        monitorDataDto.setKdig(monitorKdig);

        return new ResponseResult().success().setData(monitorDataDto);
    }

    public ResponseResult<CoreDataDto> coreData(CoreDataParam param) {
        if (tokenValid) {
            // 验证token
            TokenUtil.verifyToken();

            // 验证项目权限
            TokenUtil.verifyAuthority(param.getAccessToken(), param.getProjectCode());

            // 验证功能权限
            TokenUtil.verifyRole(E_PERMISSION_TYPE.jcad_en.toString());
        }

        // 将时间进行周一到周日补全
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtil.parseDate(param.getEndTime()));
        // 将结束时间设置为周日
        if (calendar.get(Calendar.DAY_OF_WEEK) == 1) {
            calendar.add(Calendar.WEEK_OF_MONTH, -1);
        }
        calendar.add(Calendar.WEEK_OF_MONTH, 1);
        calendar.set(Calendar.DAY_OF_WEEK, 1);
        String fillEndDate = DateUtil.format(calendar.getTime(), "yyyy-MM-dd");
        Long fillEndTime = calendar.getTimeInMillis();

        calendar.setTime(DateUtil.parseDate(param.getStartTime()));
        if (calendar.get(Calendar.DAY_OF_WEEK) == 1) {
            calendar.add(Calendar.WEEK_OF_MONTH, -1);
        }
        calendar.set(Calendar.DAY_OF_WEEK, 2);
        String fillStartDate = DateUtil.format(calendar.getTime(), "yyyy-MM-dd");

        List<String> fillXData = new ArrayList<>();
        while (calendar.getTimeInMillis() <= fillEndTime) {
            fillXData.add(DateUtil.format(calendar.getTime(), "MM.dd"));
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        CoreDataDto coreDataDto = new CoreDataDto();

//        Calendar calendar = Calendar.getInstance();
//        Long endTime = DateUtil.parseDate(param.getEndTime()).getTime();
//        calendar.setTime(DateUtil.parseDate(param.getStartTime()));
//        List<String> xData = new ArrayList<>();
//        while (calendar.getTimeInMillis() < endTime) {
//            xData.add(DateUtil.format(calendar.getTime(), "MM.dd"));
//            calendar.add(Calendar.DAY_OF_MONTH, 1);
//        }

        // 查找时间段内，该项目的数据
        List<Monitordata> monitordataList = monitordataMapper.findByCode(param.getProjectCode(), fillStartDate, fillEndDate);
        // 获取核心检测数据
        CoreMonitorDataDto coreMonitorDataDto = new CoreMonitorDataDto();
        coreMonitorDataDto.setEndDate(fillEndDate);
        coreMonitorDataDto.setStartDate(fillStartDate);
        coreMonitorDataDto.setXData(fillXData);
        MonitorDataDto.MonitorYData monitorTem = new MonitorDataDto.MonitorYData();
        MonitorDataDto.MonitorYData monitorRainfall = new MonitorDataDto.MonitorYData();
        MonitorDataDto.MonitorYData monitorPgv = new MonitorDataDto.MonitorYData();
        MonitorDataDto.MonitorYData monitorAvvig = new MonitorDataDto.MonitorYData();
        MonitorDataDto.MonitorYData monitorAkdig = new MonitorDataDto.MonitorYData();
        MonitorDataDto.MonitorYData monitorHumity = new MonitorDataDto.MonitorYData();
        List<String> yTemList = new ArrayList<>();
        List<String> yRainfallList = new ArrayList<>();
        List<String> yPgvList = new ArrayList<>();
        List<String> yAvvigList = new ArrayList<>();
        List<String> yAkdigList = new ArrayList<>();
        List<String> yHumityList = new ArrayList<>();
        calendar.setTime(DateUtil.parseDate(fillStartDate));
        while (calendar.getTimeInMillis() <= fillEndTime) {
            Boolean has = false;
            for (Monitordata monitordata : monitordataList) {
                String d = DateUtil.formatDate(calendar.getTime());
                if (monitordata.getDate().contains(d)) {
                    has = true;
                    // 遍历数据，解析vvig数据
                    String overalldd = monitordata.getOveralldd();
                    String[] overalldds = overalldd.split(";");
                    for (String key : overalldds) {
                        String[] vs = key.split(":");
                        if (vs[0].equals("Rain"))
                            yRainfallList.add(vs[1]);
                        else if (vs[0].equals("temperatue"))
                            yTemList.add(vs[1]);
                        else if (vs[0].equals("PGV"))
                            yPgvList.add(vs[1]);
                        else if (vs[0].equals("humity"))
                            yHumityList.add(vs[1]);
                        //Rain:2.2;temperatue:5.17;PGV:2.5;Pressure:91.27;humity:68.05;lamination:58318;PGA:5.1;
                    }
                    String avvig = monitordata.getAvvig();
                    if (StrUtil.isNotEmpty(avvig)) {
                        avvig = avvig.trim();
                        if (avvig.endsWith(";"))
                            avvig = avvig.substring(0, avvig.length() - 1);
                        String[] avvigs = avvig.split(":");
                        if (avvigs.length == 2) {
                            if (avvigs[1].compareTo("100") > 0)
                                yAvvigList.add(null);
                            else
                                yAvvigList.add(avvigs[1]);
                        }
                    }

                    String akdig = monitordata.getAkdig();
                    if (StrUtil.isNotEmpty(akdig)) {
                        akdig = akdig.trim();
                        if (akdig.endsWith(";"))
                            akdig = akdig.substring(0, akdig.length() - 1);
                        String[] akdigs = akdig.split(":");
                        if (akdigs.length == 2) {
                            if (akdigs[1].compareTo("100") > 0)
                                yAkdigList.add(null);
                            else
                                yAkdigList.add(akdigs[1]);
                        }
                    }
                }
            }
            if (!has) {
                yRainfallList.add(null);
                yTemList.add(null);
                yPgvList.add(null);
                yAvvigList.add(null);
                yAkdigList.add(null);
                yHumityList.add(null);
            }
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        monitorTem.setYData(yTemList);
        monitorAkdig.setYData(yAkdigList);
        monitorAvvig.setYData(yAvvigList);
        monitorPgv.setYData(yPgvList);
        monitorRainfall.setYData(yRainfallList);
        monitorHumity.setYData(yHumityList);
        coreMonitorDataDto.setAkdig(monitorAkdig);
        coreMonitorDataDto.setAvvig(monitorAvvig);
        coreMonitorDataDto.setTem(monitorTem);
        coreMonitorDataDto.setPgv(monitorPgv);
        coreMonitorDataDto.setRainfall(monitorRainfall);
        coreMonitorDataDto.setHumity(monitorHumity);

        // 获取预警信息
        List<WarningDto> warningList = alarmmsgMapper.findByCode(param.getProjectCode(), param.getStartTime(), param.getEndTime());
        for (WarningDto dto : warningList) {
            StringBuffer stringBuffer = new StringBuffer();
            if (dto.getAlarmDj().equals("I"))
                stringBuffer.append("一级预警");
            else if (dto.getAlarmDj().equals("II"))
                stringBuffer.append("二级预警");
            else if (dto.getAlarmDj().equals("III"))
                stringBuffer.append("三级预警");
            else if (dto.getAlarmDj().equals("IV"))
                stringBuffer.append("四级预警");
            stringBuffer.append(" ");
            stringBuffer.append(dto.getCreatedTime());
            stringBuffer.append(" ");
            stringBuffer.append(dto.getAlarmName());
            stringBuffer.append(" ");
            stringBuffer.append(dto.getJdzb());
            stringBuffer.append(dto.getAlarmMax());
            dto.setContent(stringBuffer.toString());
        }

        coreDataDto.setCoreMonitorData(coreMonitorDataDto);
        coreDataDto.setWarningList(warningList);

        return new ResponseResult().success().setData(coreMonitorDataDto);
    }

    public ResponseResult<DownLoadReportDto> downloadReport(DownloadReportParam param) {
        if (tokenValid) {
            // 验证token
            TokenUtil.verifyToken();

            // 验证功能权限
            TokenUtil.verifyRole(E_PERMISSION_TYPE.vbad_en.toString());

            // 验证项目权限
            TokenUtil.verifyAuthority(param.getAccessToken(), param.getProjectCode());
        }

        List<DownLoadReportDto> list = new ArrayList<>();

        // 获取根据项目获取文件夹下
        Project project = projectMapper.findByCode(param.getProjectCode());
//        if(tokenValid)
//            reportUrl = project.getAppletUrl();
        String path = project.getProjectReseve();
        File file = new File(path);
        if (file.exists()) {
            // 如果文件夹存在
            File fs[] = file.listFiles();
            for (File f : fs) {
                if (!f.isDirectory()) {
                    DownLoadReportDto downLoadReportDto = new DownLoadReportDto();
                    // 获取创建时间
                    Path p = Paths.get(path);
                    BasicFileAttributeView basicFileAttributeView = Files.getFileAttributeView(p, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
                    String createdTime = null;
                    try {
                        BasicFileAttributes attributes = basicFileAttributeView.readAttributes();
                        Long l = attributes.creationTime().toMillis();
//                        if (StrUtil.isNotEmpty(param.getStartTime()) && StrUtil.isNotEmpty(param.getEndTime())) {
//                            long start = DateUtil.parseDate(param.getStartTime()).getTime();
//                            long end = DateUtil.parseDate(param.getEndTime()).getTime() + 1000 * 60 * 60 * 24;
//                            if (l < start || l > end)
//                                continue;
//                        }
                        createdTime = DateUtil.formatDateTime(new Date(l));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    downLoadReportDto.setCreatedTime(createdTime);
                    downLoadReportDto.setName(f.getName());
                    downLoadReportDto.setDownloadUrl(reportUrl + project.getCode() + "/report/" + f.getName());
                    list.add(downLoadReportDto);
                }
            }
        }
        return new ResponseResult().success().setData(list);
    }

    public ResponseResult<List<WarningDto>> getWarningList(GetWarningListParam param) {
        if (tokenValid) {
            // 验证token
            TokenUtil.verifyToken();

            // 验证项目权限
            TokenUtil.verifyAuthority(param.getAccessToken(), param.getProjectCode());
        }

        // 获取预警信息
        List<WarningDto> warningList = alarmmsgMapper.findByCode(param.getProjectCode(), param.getTime(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        for (WarningDto dto : warningList) {
            StringBuffer stringBuffer = new StringBuffer();
            if (dto.getAlarmDj().equals("I"))
                stringBuffer.append("一级预警");
            else if (dto.getAlarmDj().equals("II"))
                stringBuffer.append("二级预警");
            else if (dto.getAlarmDj().equals("III"))
                stringBuffer.append("三级预警");
            else if (dto.getAlarmDj().equals("IV"))
                stringBuffer.append("四级预警");
            stringBuffer.append(" ");
            stringBuffer.append(dto.getCreatedTime());
            stringBuffer.append(" ");
            stringBuffer.append(dto.getAlarmName());
            stringBuffer.append(" ");
            stringBuffer.append(dto.getJdzb());
            stringBuffer.append(dto.getAlarmMax());
            dto.setContent(stringBuffer.toString());
        }
        return new ResponseResult().success().setData(warningList);
    }
}
